package com.ruoyi.labdata.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.labdata.domain.LabFile;
import com.ruoyi.labdata.domain.LabOrgnization;
import com.ruoyi.labdata.service.ILabFileService;
import com.ruoyi.labdata.service.ILabOrgnizationService;
import com.ruoyi.labdata.service.ILabTwoDimensionalCodeService;
import com.ruoyi.pdf.receipt.PdfGenerator;
import com.ruoyi.pdf.receipt.PdfGeneratorOccupation;
import com.ruoyi.pdf.receipt.PdfGeneratorReceipt;
import com.ruoyi.pdf.receipt.PdfGeneratorSafetyCorrective;

/**
 * 仪器文件Controller
 * 
 * @author winner pan
 * @date 2022-02-22
 */
@RestController
@RequestMapping("/labdata/labFile")
public class LabFileController extends BaseController
{
    @Autowired
    private ILabFileService labFileService;
    @Autowired
	private ILabOrgnizationService labOrgnizationService;
    @Autowired
    private PdfGeneratorReceipt pdfGeneratorReceipt;
    @Autowired
    private PdfGeneratorOccupation pdfGeneratorOccupation;
    @Autowired
    private PdfGeneratorSafetyCorrective pdfGeneratorSafetyCorrective;
    
    @Autowired
    private ILabTwoDimensionalCodeService labTwoDimensionalCodeService;

    /**
     * 查询仪器文件列表
     */
    //@PreAuthorize("@ss.hasPermi('labdata:labFile:list')")
    @GetMapping("/list")
    public TableDataInfo list(LabFile labFile)
    {
        startPage();
        List<LabFile> list = labFileService.selectLabFileList(labFile);
        return getDataTable(list);
    }

    /**
     * 导出仪器文件列表
     */
   // @PreAuthorize("@ss.hasPermi('labdata:labFile:export')")
    @Log(title = "仪器文件", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LabFile labFile)
    {
        List<LabFile> list = labFileService.selectLabFileList(labFile);
        ExcelUtil<LabFile> util = new ExcelUtil<LabFile>(LabFile.class);
        return util.exportExcel(list, "labFile");
    }

    /**
     * 获取仪器文件详细信息
     */
    //@PreAuthorize("@ss.hasPermi('labdata:labFile:query')")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId)
    {
        return AjaxResult.success(labFileService.selectLabFileById(fileId));
    }

    /**
     * 新增仪器文件
     */
    //@PreAuthorize("@ss.hasPermi('labdata:labFile:add')")
    @Log(title = "仪器文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LabFile labFile)
    {
        return toAjax(labFileService.insertLabFile(labFile));
    }

    /**
     * 修改仪器文件
     */
    //@PreAuthorize("@ss.hasPermi('labdata:labFile:edit')")
    @Log(title = "仪器文件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LabFile labFile)
    {
        return toAjax(labFileService.updateLabFile(labFile));
    }

    /**
     * 删除仪器文件
     */
   // @PreAuthorize("@ss.hasPermi('labdata:labFile:remove')")
    @Log(title = "仪器文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fileIds}")
    public AjaxResult remove(@PathVariable Long[] fileIds)
    {
        return toAjax(labFileService.deleteLabFileByIds(fileIds));
    }
    
    @GetMapping(value = "/image")
    public String downloadImage(Long fileId, HttpServletRequest request, HttpServletResponse response) {
        //String fileName = "123.JPG";
    	LabFile labFile  = labFileService.selectLabFileById(fileId);
    	if(labFile==null){
    		throw new RuntimeException("未能查找到该文件ID:" + fileId);
    	}
    	String fileUrl = RuoYiConfig.getProfile() + StringUtils.substringAfter(labFile.getFilePath(), Constants.RESOURCE_PREFIX);
        File file = new File(fileUrl);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.setHeader("Content-Type","video/mpeg4"); 
                try {
					response.addHeader("Content-Disposition",
					        "attachment;fileName=" +  FileUtils.setFileDownloadHeader(request, labFile.getFileName()));
				} catch (UnsupportedEncodingException e1) {
					response.addHeader("Content-Disposition",
					        "attachment;fileName=" +  labFile.getFileName());
					e1.printStackTrace();
				}// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    //System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        return null;
    }
    
    @GetMapping(value = "/orgQR")
    public String orgQR(Long id, HttpServletRequest request, HttpServletResponse response) {
    	LabOrgnization labOrgnization = labOrgnizationService.selectLabOrgnizationById(id);
    	if(labOrgnization.getQrCodePath()==null){
    		String qrCode = labTwoDimensionalCodeService.getTwoDimensionalCode(labOrgnization.getOrgCode()+labOrgnization.getCreateYear());
    		String qrCodePath = labTwoDimensionalCodeService.encodeNoReturn(qrCode, "1");
    		labOrgnization.setQrCode(qrCode);
    		labOrgnization.setQrCodePath(qrCodePath);
    		labOrgnizationService.updateLabOrgnization(labOrgnization);
    	}
       
        String fileUrl = RuoYiConfig.getProfile() + StringUtils.substringAfter(labOrgnization.getQrCodePath(), Constants.RESOURCE_PREFIX);
        File file = new File(fileUrl);
        if(StringUtils.isEmpty(labOrgnization.getQrCodePath())|| !file.exists()){
        	String qrCode = labTwoDimensionalCodeService.getTwoDimensionalCode(labOrgnization.getOrgCode()+labOrgnization.getCreateYear());
    		String qrCodePath = labTwoDimensionalCodeService.encodeNoReturn(qrCode, "1");
    		labOrgnization.setQrCode(qrCode);
    		labOrgnization.setQrCodePath(qrCodePath);
    		labOrgnizationService.updateLabOrgnization(labOrgnization);
    		fileUrl = RuoYiConfig.getProfile() + StringUtils.substringAfter(labOrgnization.getQrCodePath(), Constants.RESOURCE_PREFIX);
    		file = new File(fileUrl);
        }
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setHeader("Content-Type","video/mpeg4");
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" + labOrgnization.getOrgCode()+".png");// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                //System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
    
    @GetMapping(value = "/printReceipt")
    public String printReceiptDoc(Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	return getGeneralFile(id, pdfGeneratorReceipt, response);
    }
    
    @GetMapping(value = "/printOccupation")
    public String printOccupation(Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	return getGeneralFile(id, pdfGeneratorOccupation, response);
    }
    
    @GetMapping(value = "/printSafetyCorrective")
    public String printSafetyCorrective(Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	return getGeneralFile(id, pdfGeneratorSafetyCorrective, response);
    }

	private String getGeneralFile(Long id, PdfGenerator pdfGenerator,HttpServletResponse response)
			throws Exception, UnsupportedEncodingException {
		pdfGenerator.run(id);
        String fileUrl = RuoYiConfig.getProfile() + "/pdf/"+pdfGenerator.getFileName(id)+".pdf";
        File file = new File(fileUrl);
        if(!file.exists()){
        	throw new RuntimeException("打印文件没有生成成功或者文件路径配置错误. 路径:"+fileUrl);
        }
        String fileName = URLEncoder.encode(pdfGenerator.getFileName(id)+".pdf","UTF-8");
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition",
                "attachment;fileName=" + fileName);// 设置文件名
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
	}
}
